import React, { Component, useRef, useState } from 'react';
// import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import {
  Button,
  Tag,
  Space,
  Menu,
  Table,
  Dropdown,
  DatePicker,
  Popconfirm,
  message,
} from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import {
  SettingOutlined,
  EyeOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
// import request from 'umi-request';
import { getRole, delRole } from '@/api/role';
import AddRole from './component/AddRole';
import UpdateRole from './component/UpdateRole';
import Role from './component/Role';
interface Props {}
interface State {}

export default () => {
  const confirm = (e: any) => {
    console.log(e);
    del(e.roleId);
    // console.log(res);
    // message.success('删除成功');
  };

  function cancel(e: any) {
    console.log(e);
    message.error('取消删除');
  }
  const { RangePicker } = DatePicker;
  type GithubIssueItem = {
    url: string;
    id: number;
    number: number;
    title: string;
    labels: {
      name: string;
      color: string;
    }[];
    state: string;
    comments: number;
    created_at: string;
    updated_at: string;
    closed_at?: string;
  };
  const columns: ProColumns<GithubIssueItem>[] = [
    // {
    //   dataIndex: 'index',
    //   valueType: 'indexBorder',
    //   width: 48,
    // },
    {
      title: '角色',
      dataIndex: 'roleName',
      copyable: true,
    },

    {
      title: '描述',
      dataIndex: 'remark',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateRange',
      // hideInSearch: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          if (value) {
            return {
              startTime: value[0],
              endTime: value[1],
            };
          } else {
            return {
              startTime: '',
              endTime: '',
            };
          }
        },
      },
      renderFormItem: () => {
        return <RangePicker />;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <SettingOutlined
          onClick={() => change(record)}
          key="editable"
          style={{ color: '#4A9FF5' }}
        />,
        <EyeOutlined
          onClick={() => changShow(record)}
          key="view"
          style={{ color: '#42B983' }}
        />,
        // <a href={record.url} target="_blank" rel="noopener noreferrer">
        //   查看
        // </a>,
        <Popconfirm
          key="confirm"
          title="确定删除此条数据吗？"
          onConfirm={() => confirm(record)}
          onCancel={cancel}
          okText="确定"
          cancelText="取消"
        >
          <DeleteOutlined key="del" style={{ color: 'red' }} />
        </Popconfirm>,
      ],
    },
  ];
  const [record, setRecord] = useState({});
  const [visible, setVisible] = useState<boolean>(false);
  //打开抽屉
  const change = (item: any) => {
    setRecord(item);
    setVisible(true);
  };

  //关闭抽屉
  const close = () => {
    setRecord({});
    setVisible(false);
  };

  const del = async (id: string) => {
    console.log(id, 'resDel');
    const res = await delRole(id);
    console.log(res, 'del');
    if (res.status == 200) {
      message.success('删除成功');
      actionRef.current?.reload();
    } else {
      message.error('删除失败');
    }
  };
  const actionRef = useRef<ActionType>();
  const delAll = (a: any) => {
    let arr = a.selectedRowKeys;
    for (let i = 0; i < arr.length; i++) {
      del(arr[i]);
    }
  };
  const reload = () => {
    actionRef.current?.reload();
  };

  //角色详细信息
  const [visibleRole, setVisibleRole] = useState<boolean>(false);
  const changShow = (item: any) => {
    setRecord(item);
    setVisibleRole(true);
  };
  const closeRole = () => {
    setRecord({});
    setVisibleRole(false);
  };
  return (
    <div>
      <Role
        reload={reload}
        record={record}
        closeRole={closeRole}
        visibleRole={visibleRole}
      ></Role>
      <UpdateRole
        close={close}
        reload={reload}
        record={record}
        visible={visible}
      ></UpdateRole>
      <ProTable<GithubIssueItem>
        columns={columns}
        actionRef={actionRef}
        // request={async (params = {}, sort, filter) => {
        //   const { data } = await getRole()
        //   console.log(data);

        // }}
        request={async (params = {}, sort, filter) => {
          console.log(params);
          const { startTime, endTime, roleName } = params;

          let searchData = {
            // pageNum: current ? current + '' : '1',
            // pageSize: pageSize ? pageSize + '' : '5',
            createTimeFrom: startTime ? startTime : '',
            createTimeTo: endTime ? endTime : '',
            roleName: roleName ? roleName : '',
          };
          console.log(searchData);

          const { data } = await getRole(searchData);
          console.log(data, 'ata');
          return {
            data: data.rows,
            success: true,
            total: data.total,
          };
        }}
        rowSelection={{
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          // 注释该行则默认不显示下拉选项
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="roleId"
        search={{
          labelWidth: 'auto',
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        // headerTitle={
        //   <>
        //     <AddRole></AddRole>
        //     <Button>删除</Button>
        //   </>
        // }
        headerTitle={
          <>
            <AddRole reload={reload}></AddRole>
            {/* <Button>删除</Button> */}
          </>
        }
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => {
          // console.log(selectedRowKeys, 'ss');
          // setRoleId([...selectedRowKeys])
          return (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                {/* <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a> */}
              </span>
            </Space>
          );
        }}
        tableAlertOptionRender={(a) => {
          // console.log(a);
          return (
            <Space size={16}>
              <Button onClick={() => delAll(a)}>批量删除</Button>
            </Space>
          );
        }}
      />
    </div>
  );
};
